<template>
  <a-modal v-model:open="open" :title="formState.id ? '编辑学生': '新增学生'" @ok="handleOk" @cancel="handleCancel">
    <a-form ref="formRef" :model="formState" style="margin-top: 16px">
      <a-form-item label="所属班级" name="category_id" :rules="[{ required: true, message: '请选择班级' }]">
        <a-select
          v-model:value="formState.category_id"
          placeholder="请选择班级"
        >
          <a-select-option v-for="category in categoryList" :key="category.id" :value="category.id">
            {{ category.category_name }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="姓名" name="user_name" :rules="[{ required: true, message: '请输入姓名' }]">
        <a-input v-model:value="formState.user_name" placeholder="请输入姓名" />
      </a-form-item>
      <a-form-item label="学号" name="account" :rules="[{ required: true, message: '请输入学号' }]">
        <a-input v-model:value="formState.account" placeholder="请输入学号" />
      </a-form-item>
      <a-form-item label="状态" name="status" :rules="[{ required: true, message: '请选择状态' }]">
        <a-radio-group v-model:value="formState.status" placeholder="请选择状态">
          <a-radio value="1">启用</a-radio>
          <a-radio value="0">禁用</a-radio>
        </a-radio-group>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { fetchStudentCreateOrUpdate } from '@/api/student'
import { message } from 'ant-design-vue'

const emits = defineEmits(['refresh'])

const open = ref(false)
const categoryList = ref<{ category_name: string; id: number }[]>([])
const handleOk = () => {
  formRef.value.validate().then(async () => {
    const res = await fetchStudentCreateOrUpdate(formState.value)
    if (res.data.code == '200') {
      message.success(`${formState.value.id ? '修改' : '新增'}成功`)
      emits('refresh')
      reset()
      open.value = false
    } else {
      message.error(res.data.message)
    }
  })
}
const handleCancel = () => {
  reset()
  open.value = false
}
const reset = () => {
  Object.keys(formState.value).forEach(key => {
    formState.value[key] = undefined
  })
  formState.value.status = '1'
}
const openModal = (record: any, category_list: any[]) => {
  categoryList.value = category_list
  if (record) {
    Object.keys(formState.value).forEach(key => {
      formState.value[key] = record[key]
    })
    formState.value.status = record.status_str === '开启' ? '1' : '0'
  }
  open.value = true
}

const formRef = ref()
const formState = ref<any>({
  id: undefined,
  account: undefined,
  user_name: undefined,
  category_id: undefined,
  status: '1'
})

defineExpose({ openModal })
</script>

<style scoped lang="scss"></style>
